package com.itstu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.itstu.gulimall.product.service.CategoryBrandRelationService;
import com.itstu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itstu.common.utils.PageUtils;
import com.itstu.common.utils.Query;

import com.itstu.gulimall.product.dao.CategoryDao;
import com.itstu.gulimall.product.entity.CategoryEntity;
import com.itstu.gulimall.product.service.CategoryService;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }
    //TODO 产生堆外内存溢出，lettuce作为操作redis的客户端，他使用netty进行网络通信，netty是默认使用java程序分配的虚拟机内存大小
    // 解决方案，1. 升级lettuce 2. 使用jedis

    /**
     * TODO Spring-Cache解决方案
     * 1） 读模式
     *    缓存穿透：查询null，解决： 缓存空数据 配置spring.cache.redis.cache-null-values=true
     *    缓存击穿：大量并发查询一个刚好过期的数据。解决： 加锁sync = true（默认为false）
     *    缓存雪崩：大量的key同时过期。解决：加随机时间。加上过期时间 配置spring.cache.redis.time-to-live=3600000
     * 2） 写模式（主要是保证缓存和数据库的一致）
     *      1）读写锁
     *      2）引入canal，感知到mysql的更新，去更新缓存
     *      3）读多写多的，直接去数据库查询
     * 总结：
     *      常规数据（读多写少，即时性和一致性要求不高的数据）；完全可使用Spring-Catch（只要有过期时间就已足够）
     *      特殊数据：特殊设计
     * @return
     */
    @Override
    @Cacheable(value = "category",key = "#root.methodName",sync = true)
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("db查询！！！！！！！！！！！！！！！！！！！！！！！！！！！");
        List<CategoryEntity> level1Category = this.getLevel1Category();// 这里省略了  this.
        // 封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Category.stream().collect(Collectors.toMap(k -> {
            return k.getCatId().toString();
        }, v -> {
            // 查到每一个一级分类的二级分类
            List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 找当前二级分类的三级分类封装成VO
                    List<CategoryEntity> categoryEntities1 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    List<Catelog2Vo.Catalog3Vo> catelog3Vos = null;
                    if (categoryEntities1 != null){
                        catelog3Vos = categoryEntities1.stream().map(l3 -> {
                            Catelog2Vo.Catalog3Vo catelog3Vo = new Catelog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catelog2Vo.setCatalog3List(catelog3Vos);
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }



    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        /**
         * 1. 空结果缓存，解决缓存穿透
         * 2. 设置过期时间（加随机值），解决缓存雪崩
         * 3. 加锁，解决缓存击穿
         */
        // 加入缓存逻辑，缓存中的数据是json字符串
        // TODO 因为json跨语言，跨平台兼容
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        // 缓存没有查询数据库
        if (StringUtils.isEmpty(catalogJson)){
            System.out.println("缓存不命中，进入db方法查数据库。。。。");
            // 有三种方法，1.直接从数据库获得  2. 加本地锁  3.redis分布式锁
            getCatalogJsonFromDbWithRedisLock();
//            getCatalogJsonFromDbWithLocalLock();
//            getDataFromDb();
            // 查询到的数据在放入缓存，将对象转化为json在放入缓存中
        }
        // 转为指定的对象
        System.out.println("无db方法缓存命中。。00000。。");
        Map<String, List<Catelog2Vo>> result= JSON.parseObject(catalogJson,new TypeReference< Map<String, List<Catelog2Vo>>>(){});

        return result;
    }
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock()  {
        // TODO 此处是否加读写锁更合适
        RLock rLock = redisson.getLock("CatalogJson-lock");
        rLock.lock();
        System.out.println("获取分布式锁成功。。。。");
        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        }finally {
            rLock.unlock();
        }
        // 占分布式锁
        return dataFromDb;
    }
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock()  {
        String uuid = UUID.randomUUID().toString();
        // 占分布式锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        if (lock){
            System.out.println("获取分布式锁成功。。。。");
            // 加锁成功,执行业务
            // 设置过期时间.如果不设置成原子操作可能会出现问题
           // redisTemplate.expire("lock",30,TimeUnit.SECONDS);
            Map<String, List<Catelog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            }finally {
                // 删除锁
                // 获取锁+对比成功删除锁要是原子操作，使用lua脚本解锁
                String s1 = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end ";
                redisTemplate.execute(new DefaultRedisScript<Integer>(s1,Integer.class),Arrays.asList("lock"),uuid);
            }

//            String s = redisTemplate.opsForValue().get("lock");
//            if (uuid.equals(s)){
//                redisTemplate.delete("lock" );
//            }
            return dataFromDb;
        }else {
            System.out.println("获取分布式锁失败。。。等待重试。");
            // 加锁失败，重试
            // 休眠
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock();
        }


    }
    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if (!StringUtils.isEmpty(catalogJson)){
            System.out.println("有db方法缓存命中。11111。。");
            Map<String, List<Catelog2Vo>> result= JSON.parseObject(catalogJson,new TypeReference< Map<String, List<Catelog2Vo>>>(){});
            return result;
        }
        System.out.println("db查询！！！！！！！！！！！！！！！！！！！！！！！！！！！");
        List<CategoryEntity> level1Category = getLevel1Category();// 这里省略了  this.
        // 封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Category.stream().collect(Collectors.toMap(k -> {
            return k.getCatId().toString();
        }, v -> {
            // 查到每一个一级分类的二级分类
            List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 找当前二级分类的三级分类封装成VO
                    List<CategoryEntity> categoryEntities1 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    List<Catelog2Vo.Catalog3Vo> catelog3Vos = null;
                    if (categoryEntities1 != null){
                        catelog3Vos = categoryEntities1.stream().map(l3 -> {
                            Catelog2Vo.Catalog3Vo catelog3Vo = new Catelog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catelog2Vo.setCatalog3List(catelog3Vos);
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        String s = JSON.toJSONString(parent_cid);
        // 给缓存设置过期时间
        redisTemplate.opsForValue().set("catalogJson",s,1, TimeUnit.DAYS);
        return parent_cid;
    }
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {
        synchronized (this){
           return getDataFromDb();
        }

    }

    @Override
    @Cacheable(value = {"category"},key = "#root.methodName",sync = true)// 代表当前方法的结果需要缓存，如果缓存中有，方法就不用调用。
    public List<CategoryEntity> getLevel1Category() {
        System.out.println("getLevel1Category方法被调用了");
        // 给parent_cid 建立索引能减少db的响应时间
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));

        return entities;
    }



    @Override
    public List<CategoryEntity> listWithTree() {
        // 1 查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2 组装成树形结构
        // 2.1 找到所有的一级分类
        List<CategoryEntity> levelMenus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu)->{
                    menu.setChildren(getChildrens(menu,entities));
                    return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort() == null?0:menu1.getSort()) - (menu2.getSort() == null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return  levelMenus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 1. 检查当前删除菜单能否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);


        return parentPath.toArray(new Long[parentPath.size()]);
    }


    /**
     * 级联更新所有数据
     * @CacheEvict缓存失效模式
     * 可以设置删除的分区
     * @param category
     */
    @Override
    @CacheEvict(value = "category",allEntries = true)
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCascade(category.getCatId(),category.getName());

    }



    // 递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){

        List<CategoryEntity> children = all.stream().filter(categoryEntity ->
//             categoryEntity.getParentCid() == root.getCatId()
//              categoryEntity.getParentCid().equals(root.getCatId())
                // TODO 修改判断式，使的判断结果更加准确
              categoryEntity.getParentCid() - root.getCatId() == 0
        ).map(categoryEntity -> {
            List<CategoryEntity> ch= getChildrens(categoryEntity, all);
            categoryEntity.setChildren(ch);
//            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //菜单的排序
            return (menu1.getSort() == null?0:menu1.getSort()) - (menu2.getSort() == null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return children;


    }

    //225,25,2
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);

        // 递归调用
        if(byId.getParentCid()!= 0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;

    }

    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<>());
        List<CategoryEntity> collect = entities.stream().filter(entity ->
             entity.getParentCid() == 0
        ).map(l1 -> {
            List<CategoryEntity> children = this.findChildren(entities, l1);
            l1.setChildren(children);
            return l1;
        }).collect(Collectors.toList());
        return collect;
    }

    private List<CategoryEntity> findChildren(List<CategoryEntity> entities, CategoryEntity l1) {
        List<CategoryEntity> childrens = entities.stream().filter(entity ->
              entity.getParentCid() - l1.getCatId() == 0
        ).map(m -> {
            List<CategoryEntity> children = this.findChildren(entities, m);
            m.setChildren(children);
            return m;
        }).collect(Collectors.toList());
        return childrens;
    }

}